﻿using Message_Board.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Message_Board.Controllers
{
    public class MessagesController : Controller
    {
        private MessageDBContext db = new MessageDBContext();
        int pagenum = 6;
        // GET: Messages
        public ActionResult Index(string messageType,string searchString,string currentPage)//主页
        {
            if (String.IsNullOrEmpty(currentPage))
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            if (int.Parse(currentPage)==0)
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            ViewBag.currentPage = int.Parse(currentPage);
            var TypeLst = new List<string>();
            var TypeQry = from d in db.Messages orderby d.MessageType select d.MessageType ;
            TypeLst.AddRange(TypeQry.Distinct());    //去重
            ViewBag.messageType = new SelectList(TypeLst);
            var messages = from m in db.Messages where m.Number==1 select m;
            if (!String.IsNullOrEmpty(messageType))
            { messages = messages.Where(x => x.MessageType == messageType); }
            if (!String.IsNullOrEmpty(searchString))
            { messages = messages.Where(s => s.Subject.Contains(searchString)); }
            int count=messages.ToList().Count;
            int i = count / pagenum;
            if (i != 0 &&(count%pagenum!=0))
                i++;
            if (count <= 5)
                i++;
            ViewBag.maxPage = i;
            if (int.Parse(currentPage) > i)
            {
                return RedirectToAction("Index", "Messages");
            }
            messages=messages.OrderByDescending(s => s.Time);
            int lostpage = i - int.Parse(currentPage);
            int lostnum = count - (i - 1) * pagenum + (lostpage - 1) * pagenum;
            if (i > 1)
            {
                messages = messages.Take(count - lostnum);
                messages = messages.Skip((int.Parse(currentPage) - 1) * pagenum);
            }
            return View(messages.ToList());
        }

        public ActionResult Details(string subject, string currentPage)//主题明细
        {
            if (String.IsNullOrEmpty(currentPage))
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            if (int.Parse(currentPage) == 0)
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            ViewBag.currentPage = int.Parse(currentPage);
            var messages = from m in db.Messages where m.Subject==subject select m;
            messages=messages.OrderBy(s => s.Number);
            ViewBag.Subject = subject;
            ViewBag.MessageType = messages.First().MessageType;
            ViewBag.Content = messages.First().Content;
            ViewBag.UserName = messages.First().UserName;
            ViewBag.Time = messages.First().Time;
            ViewBag.ID = messages.First().ID;
            if (messages == null)
            {
                return HttpNotFound();
            }
            ViewBag.Name = messages.First().UserName;
            int count = messages.ToList().Count-1;
            int i = count / pagenum;
            if (i != 0 && (count % pagenum != 0))
                i++;
            if (count <= 5)
                i++;
            ViewBag.maxPage = i;
            if (int.Parse(currentPage) > i)
            {
                string url = "/Messages/Details?subject="+subject;
                return Redirect(url);
            }
            int lostpage = i - int.Parse(currentPage);
            int lostnum = count - (i - 1) * pagenum + (lostpage - 1) * pagenum;
            if (i > 1)
            {
                messages = messages.Take(count - lostnum);
                messages = messages.Skip((int.Parse(currentPage) - 1) * pagenum);
            }
            return View(messages.ToList());
        }

        public ActionResult ReplyMyself(string currentPage)//查看回复自己的消息
        {
            if (String.IsNullOrEmpty(currentPage))
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            if (int.Parse(currentPage) == 0)
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            ViewBag.currentPage = int.Parse(currentPage);
            string name = "";
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
                name = HttpContext.Application["userName"].ToString();
            ViewBag.userName = name;
            var messages = from m in db.Messages where m.ReplyName == name select m;
            messages = messages.OrderByDescending(s => s.Time);
            int count = messages.ToList().Count - 1;
            int i = count / pagenum;
            if (i != 0 && (count % pagenum != 0))
                i++;
            if (count <= 5)
                i++;
            ViewBag.maxPage = i;
            if (int.Parse(currentPage) > i)
            {
                return RedirectToAction("PersonalSubject", "Messages");
            }
            int lostpage = i - int.Parse(currentPage);
            int lostnum = count - (i - 1) * pagenum + (lostpage - 1) * pagenum;
            if (i > 1)
            {
                messages = messages.Take(count - lostnum);
                messages = messages.Skip((int.Parse(currentPage) - 1) * pagenum);
            }
            return View(messages.ToList());
        }

        public ActionResult Personal()//个人页
        {
            string name = "";
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
               name = HttpContext.Application["userName"].ToString();
            ViewBag.userName = name;
            var messages = from m in db.Messages where m.UserName == name select m;
            messages = messages.OrderByDescending(s => s.Time);
            return View(messages.ToList());
        }

        public ActionResult PersonalSubject(string currentPage)//个人所发表的主题
        {
            if (String.IsNullOrEmpty(currentPage))
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            if (int.Parse(currentPage) == 0)
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            ViewBag.currentPage = int.Parse(currentPage);

            string name = "";
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
                name = HttpContext.Application["userName"].ToString();
            ViewBag.userName = name;
            var messages = from m in db.Messages where m.UserName == name&&m.Number==1 select m;
            if (messages == null)
            {
                return HttpNotFound();
            }
            messages = messages.OrderByDescending(s => s.Time);
            int count = messages.ToList().Count - 1;
            int i = count / pagenum;
            if (i != 0 && (count % pagenum != 0))
                i++;
            if (count <= 5)
                i++;
            ViewBag.maxPage = i;
            if (int.Parse(currentPage) > i)
            {
                return RedirectToAction("PersonalSubject", "Messages");
            }
            int lostpage = i - int.Parse(currentPage);
            int lostnum = count - (i - 1) * pagenum + (lostpage - 1) * pagenum;
            if (i > 1)
            {
                messages = messages.Take(count - lostnum);
                messages = messages.Skip((int.Parse(currentPage) - 1) * pagenum);
            }
            return View(messages.ToList());
        }

        public ActionResult PersonalReply(string currentPage)//个人所发表的回复
        {
            if (String.IsNullOrEmpty(currentPage))
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            if (int.Parse(currentPage) == 0)
            {
                ViewBag.currentPage = 1;
                string s = "" + 1;
                currentPage = s;
            }
            ViewBag.currentPage = int.Parse(currentPage);
            string name = "";
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
                name = HttpContext.Application["userName"].ToString();
            ViewBag.userName = name;
            var messages = from m in db.Messages where m.UserName == name && m.Number > 1 select m;
            messages = messages.OrderByDescending(s => s.Time);
            int count = messages.ToList().Count - 1;
            int i = count / pagenum;
            if (i != 0 && (count % pagenum != 0))
                i++;
            if (count <= 5)
                i++;
            ViewBag.maxPage = i;
            if (int.Parse(currentPage) > i)
            {
                return RedirectToAction("PersonalReply", "Messages");
            }
            int lostpage = i - int.Parse(currentPage);
            int lostnum = count - (i - 1) * pagenum + (lostpage - 1) * pagenum;
            if (i > 1)
            {
                messages = messages.Take(count - lostnum);
                messages = messages.Skip((int.Parse(currentPage) - 1) * pagenum);
            }
            return View(messages.ToList());
        }
        public ActionResult Details2(int id)//留言明细
        {
            Message message = db.Messages.Find(id);
            if (message == null)
            {
                return HttpNotFound();
            }
            ViewBag.sub = message.Subject;
            return View(message);
        }
        public ActionResult Create()//发表主题
        {
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
                ViewBag.userName = HttpContext.Application["userName"].ToString();
            return View();
        }
        [HttpPost]
        public ActionResult Create(Message message)
        {
            message.UserName = HttpContext.Application["userName"].ToString();
            message.Time = DateTime.Now.ToString();
            message.Number = 1;
            message.ReplyNumber = 0;
            if (ModelState.IsValid)
            {
                db.Messages.Add(message);
                db.SaveChanges();
                return RedirectToAction("Index", "Messages");
            }

            return RedirectToAction("Create", "Messages");
        }

        public ActionResult Reply(int id)//发表回复
        {
            Message message = db.Messages.Find(id);
            HttpContext.Application.Set("replyMessage", message);
            if (HttpContext.Application["userName"].ToString() == "null" || HttpContext.Application["userName"].ToString() == null)
                return RedirectToAction("Index", "Users");
            else
                ViewBag.userName = HttpContext.Application["userName"].ToString();
            ViewBag.sub = message.Subject;
            ViewBag.type = message.MessageType;
            ViewBag.reply = message.UserName;
            return View();
        }

        [HttpPost]
        public ActionResult Reply(Message message)
        {
            Message mess = (Message)HttpContext.Application["replyMessage"];
            var a = from m in db.Messages where m.Subject == mess.Subject select m;
            a=a.OrderBy(s => s.Number);
            int num2= a.First().Number;
            a =a.OrderByDescending(s =>s.Number);
            int num = a.First().Number; 
            message.Subject = mess.Subject;
            message.MessageType = mess.MessageType;
            message.ReplyName = mess.UserName;
            message.Number = num+1;
            message.ReplyNumber = mess.Number;
            message.Time= DateTime.Now.ToString();
            message.UserName = HttpContext.Application["userName"].ToString();
            if (message.Content==null || message.Content=="")
            {
                int id = mess.ID;
                string url = "/Messages/Reply?id=" + id;
                return Redirect(url);
            }        
            db.Messages.Add(message);
            db.SaveChanges();
            return RedirectToAction("Index", "Messages");

        }

        public ActionResult DeleteSubject(string subject)//删除主题
        {
            var message = from m in db.Messages where m.Subject == subject select m;
            Message mess = message.First();
            if (mess == null)
            {
                return HttpNotFound();
            }
            return View(mess);
        }
        [HttpPost]
        public ActionResult DeleteSubject(string subject, FormCollection collection)
        {
            var messages= from m in db.Messages where m.Subject == subject select m;
            List<Message> mess = messages.ToList();
            foreach(Message item in mess)
            {
                db.Messages.Remove(item);
            }
            db.SaveChanges();
            return RedirectToAction("Personal");
        }

        public ActionResult DeleteReply(int id)//删除回复
        {
            Message message = db.Messages.Find(id);
            if (message == null)
            {
                return HttpNotFound();
            }
            return View(message);
        }
        [HttpPost]
        public ActionResult DeleteReply(int id, FormCollection collection)
        {
            Message message = db.Messages.Find(id);
            if (message == null)
            {
                return HttpNotFound();
            }
            db.Messages.Remove(message);           
            Delete(message);
            db.SaveChanges();
            return RedirectToAction("Personal");
        }

        public void Delete(Message message)//删除回复message的下一层回复
        {
            var mess = from m in db.Messages where m.Subject == message.Subject && m.ReplyNumber == message.Number && m.ReplyName == message.UserName select m;
            if (mess.Count() > 0)
            {
                foreach (Message item in mess)
                {
                    db.Messages.Remove(item);
                }
                foreach (Message item in mess)
                {
                    
                    Delete(item);
                }
            }
            else
                return;
        }

        public ActionResult Edit(int id)//修改
        {
            Message message = db.Messages.Find(id);  //查找给定主键的实体
            HttpContext.Application.Set("editMessage", message);
            if (message == null)
            {
                return HttpNotFound();
            }
            return View(message);
        }

        [HttpPost]
        public ActionResult Edit(Message message)
        {
            Message mess = (Message)HttpContext.Application["editMessage"];
            message.ID = mess.ID;
            message.Subject = mess.Subject;
            message.MessageType = mess.MessageType;
            message.ReplyName = mess.ReplyName;
            message.UserName = mess.UserName;
            message.Number = mess.Number;
            message.ReplyNumber = mess.ReplyNumber; 
            message.Time = DateTime.Now.ToString();
            if (message.Content!=null && message.Content.Length>=3 && message.Content.Length<=60)
            {
                db.Entry(message).State = EntityState.Modified;
                db.SaveChanges();
                string url = "/Messages/Details2?id=" + message.ID;
                return Redirect(url);
            }
            return View(message);
        }

        public ActionResult EditSubject(int id)//修改
        {
            Message message = db.Messages.Find(id);  //查找给定主键的实体
            HttpContext.Application.Set("editMessage", message);
            if (message == null)
            {
                return HttpNotFound();
            }
            return View(message);
        }

        [HttpPost]
        public ActionResult EditSubject(Message message)
        {
            Message mess = (Message)HttpContext.Application["editMessage"];
            message.ID = mess.ID;
            message.MessageType = mess.MessageType;
            message.ReplyName = mess.ReplyName;
            message.UserName = mess.UserName;
            message.Number = mess.Number;
            message.ReplyNumber = mess.ReplyNumber;
            message.Time = DateTime.Now.ToString();
            if (message.Content != null && message.Content.Length >= 3 && message.Content.Length <= 60)
                if (message.Subject != null && message.Subject.Length >= 3 && message.Subject.Length <= 20)
                {
                var list=from m in db.Messages where m.Subject == mess.Subject select m;
                db.Entry(message).State = EntityState.Modified;
                foreach(Message item in list)
                {
                    item.Subject = message.Subject;
                    db.Entry(item).State = EntityState.Modified;
                }
                db.SaveChanges();
                string url = "/Messages/Details2?id=" + message.ID;
                return Redirect(url);
            }
            return View(message);
        }
    }
}